package jframe.config;

import com.jfinal.config.*;
import com.jfinal.plugin.activerecord.ActiveRecordPlugin;
import com.jfinal.plugin.c3p0.C3p0Plugin;
import com.jfinal.plugin.ehcache.EhCachePlugin;
import jframe.controller.AdminController;
import jframe.controller.BlogrollController;
import jframe.controller.HomeController;
import jframe.controller.UtilController;
import jframe.model.Blogroll;
import org.apache.commons.lang.StringUtils;

/**
 * User: Ulric Qin
 * Mail: ulric.qin@gmail.com
 */
public class GlobalConfig extends JFinalConfig {

    @Override
    public void configConstant(Constants constants) {
        loadPropertyFile("config.properties");
        constants.setDevMode(getPropertyToBoolean("devMode", false));
        constants.setBaseViewPath("/WEB-INF/tpl");
    }

    @Override
    public void configRoute(Routes routes) {
        routes.add("/util", UtilController.class);
        routes.add("/admin", AdminController.class);
        routes.add("/admin/blogroll", BlogrollController.class);
        routes.add("/", HomeController.class, "home");
    }

    @Override
    public void configPlugin(Plugins plugins) {
        String host = System.getenv("MOPAAS_MYSQL4916_HOST");
        String port = System.getenv("MOPAAS_MYSQL4916_PORT");
        String dbName = System.getenv("MOPAAS_MYSQL4916_NAME");
        String username = System.getenv("MOPAAS_MYSQL4916_USERNAME");
        String password = System.getenv("MOPAAS_MYSQL4916_PASSWORD");

        C3p0Plugin c3p0Plugin;
        if (StringUtils.isNotBlank(host)) {
            // in mopass env
            c3p0Plugin = new C3p0Plugin(
                    String.format("jdbc:mysql://%s:%s/%s?autoReconnect=true&useUnicode=true&characterEncoding=utf-8", host, port, dbName),
                    username,
                    password
            );
        } else {
            c3p0Plugin = new C3p0Plugin(
                    getProperty("jdbcUrl"),
                    getProperty("jdbcUser"),
                    getProperty("jdbcPass")
            );
        }

        plugins.add(c3p0Plugin);
        ActiveRecordPlugin arp = new ActiveRecordPlugin(c3p0Plugin);
        arp.setShowSql(true);
        plugins.add(arp);
        plugins.add(new EhCachePlugin());
        arp.addMapping("blogroll", Blogroll.class);
    }

    @Override
    public void configInterceptor(Interceptors interceptors) {
    }

    @Override
    public void configHandler(Handlers handlers) {
    }
}
